
var daoFactory = require('../dao'),
    Tag = daoFactory.get('tag');

exports.mappings = mappings = [];

mappings.push({method : 'get' ,url:'tag' ,handler : get});
function get(req ,res){

    Tag.find(null ,function(err,data){
        if(err) throw err;
        res.send({data:data});
    });
}

// 取一条
mappings.push({method : 'get' ,url:'tag/:_id' ,handler : findById});
function findById(req ,res){

    Tag.findById(req.query['_id'] ,function(data){
		if(data){
			res.send(data);
		}else{
			res.send({});
		}
	});
}

mappings.push({method : 'post' ,url:'tag' ,handler : save});
function save(req ,res){

    // TODO: bug
    var param = {
        name : req.param('name')
    };
    if(req.param('_id')){
        Tag.update({_id : req.param('_id')},param,function(err ,updated){
			console.log(arguments);
            if(err){
                throw err;
            }else{
                if(updated){
                    Tag.findOne(c ,function(data){
                        res.send(data);
                    });
                }else{
                    res.send({error : '更新失败.'});
                }
            }
        });
    }else{
        var c = new Tag(param);
        c.save(function(err){
		console.log(arguments);
            if(err){
                throw err;
            }else{
                Tag.findOne(c ,function(data){
                    res.send(data);
                });
            }
        });
    }

}

mappings.push({method : 'delete' ,url:'tag' ,handler : remove});
function remove(req ,res){

    Tag.remove({_id : req.query._id} ,function(data){
		var result = {success : true};
		res.send(result);
	});
}